<?php 

/**
 * Thing评论控制器
 * @author keluo<pycorvn@yeah.net>
 * @since 2012-12-14 18:34:44
 */
class CommentController extends SCController {

	public function __construct() {
		parent::__construct();
	}

	/**
	 * 发布评论
	 * @param integer $thing_id
	 */
	public function post($thing_id) {
		($user_id = SCScabish::model('user')->checkLogin()) || $this->ajaxFail('user_not_login');
		
		$text = SCRequest::post('text');
		$pattern = '/@([^ @\|\$\\\.\'\(\)\[\]\{\}\/\*\-\+#";；、&]+)/i';
		preg_match_all($pattern, $text, $matches);
		$users = array_unique($matches[1]);
		
		SCRequest::checkPost() || $this->ajaxFail();
		$comment_id = $this->model->from('sc_comment')
			->where('thing_id = '.$thing_id)
			->insert(array(
			'thing_id' => $thing_id,
			'user_id' => $user_id,
			'text' => SCRequest::post('text'),
			'post_date' => date('Y-m-d H:i:s')		
		));
		$this->ajaxSuccess($comment_id);
	}

	/**
	 * 获取指定ID评论
	 * @param integer $comment_id 评论ID
	 */
	public function getComment($comment_id) {
		$comment = $this->model->selectOne('
			SELECT c.*, u.nickname, u.gender, u.avatar FROM sc_comment AS c
			LEFT JOIN sc_user AS u ON c.user_id = u.user_id
			WHERE c.comment_id = '.$comment_id 		
		);
		
		$comment ? $this->ajaxSuccess($comment) : $this->ajaxFail();
	}
	
	public function getComments($thing_id, $page = 1, $npp = 20) {
		SCRequest::isPost() || $this->ajaxFail();
		SCPaging::setCurrentPage($page);
		SCPaging::setRecordPerPage($npp);
		$comments = $this->model->selectPage('
			c.*, u.nickname, u.gender, u.avatar FROM sc_comment AS c
			LEFT JOIN sc_user AS u ON c.user_id = u.user_id
			WHERE c.thing_id = '.$thing_id.' ORDER BY c.post_date DESC'
		);
		$paging = SCPaging::create();
		$total_num = SCPaging::$numRecord; // 评论总数
		$this->ajaxSuccess(compact('comments', 'total_num', 'paging'));
	}
	
	public function delete($comment_id) {
		SCRequest::isPost() || $this->ajaxFail();
		($user_id = SCScabish::model('user')->checkLogin()) || $this->ajaxFail('user_not_login');
		
		$auth_user_id = $this->model->selectOne('
			SELECT t.user_id AS host_user_id, c.user_id FROM sc_comment AS c
			LEFT JOIN sc_thing AS t ON c.thing_id = t.thing_id
			WHERE c.comment_id = '.$comment_id
		);
		
		if(in_array($user_id, get_object_vars($auth_user_id))) { // thing的主人或评论者本人可删除
			$this->model->reset()->from('sc_comment')->where('comment_id = '.$comment_id)->delete();
			$this->ajaxSuccess();
		} else {
			$this->ajaxFail();
		}
	}
}